import { NextRequest } from "next/server";
import { CustomerServiceAgent } from "../../../ch11service/customer-service-agent";
import { AgentSecurity } from "../../../ch11service/security";
import { AgentMonitor } from "../../../ch11service/monitoring";

// 会话存储（生产环境应使用 Redis 或数据库）
const sessions = new Map<string, CustomerServiceAgent>();

// 安全验证实例
const security = new AgentSecurity();

// 监控实例
const monitor = new AgentMonitor();

// 移除 edge runtime，使用 nodejs（ChatOllama 需要 Node.js 环境）
// export const runtime = "edge";

export async function POST(req: NextRequest) {
  try {
    const { message, sessionId = `session-${Date.now()}` } = await req.json();

    // 1. 输入验证
    if (!message || typeof message !== 'string') {
      return Response.json({ 
        success: false, 
        error: "消息内容不能为空" 
      }, { status: 400 });
    }

    // 2. 安全检查
    const validation = security.validateInput(message);
    if (!validation.valid) {
      return Response.json({ 
        success: false, 
        error: validation.reason 
      }, { status: 400 });
    }

    // 3. 限流检查
    if (!security.checkRateLimit(sessionId, 20, 60000)) {
      return Response.json({ 
        success: false, 
        error: "请求过于频繁，请稍后再试" 
      }, { status: 429 });
    }

    // 4. 获取或创建会话 Agent
    let agent = sessions.get(sessionId);
    if (!agent) {
      agent = new CustomerServiceAgent();
      sessions.set(sessionId, agent);
    }

    // 5. 处理消息（记录响应时间）
    const startTime = Date.now();
    let result;
    let isError = false;
    
    try {
      result = await agent.processMessage(message);
    } catch (error) {
      isError = true;
      throw error;
    } finally {
      const responseTime = Date.now() - startTime;
      monitor.recordRequest(
        result?.intent?.type || "unknown",
        responseTime,
        isError,
        result?.shouldEscalate || false
      );
    }

    // 6. 如果需要升级，创建工单
    let ticketId = null;
    if (result.shouldEscalate) {
      ticketId = await agent.createTicket(
        { sessionId },
        `用户问题：${message}\n意图：${JSON.stringify(result.intent)}`
      );
    }

    return Response.json({
      success: true,
      data: {
        ...result,
        ticketId,
        sessionId
      }
    });
  } catch (error: unknown) {
    console.error("客服系统错误:", error);
    const errorMessage = error instanceof Error ? error.message : "未知错误";
    return Response.json({ 
      success: false,
      error: errorMessage 
    }, { status: 500 });
  }
}

// GET 方法：获取监控指标
export async function GET() {
  return Response.json({
    status: "ok",
    metrics: monitor.getMetrics(),
    activeSessions: sessions.size
  });
}
